/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */package com.lambkit.generator.template.impl;

import com.jfinal.kit.JavaKeyword;
import com.jfinal.kit.StrKit;
import com.jfinal.template.Engine;
import com.jfinal.template.source.FileSourceFactory;
import com.lambkit.generator.template.TemplateEngine;

import java.util.HashMap;
import java.util.Map;

public class JFinalTemplateEngine extends TemplateEngine {

	private Engine engine;
	/**
	 * 针对 Model 中七种可以自动转换类型的 getter 方法，调用其具有确定类型返回值的 getter 方法
	 * 享用自动类型转换的便利性，例如 getInt(String)、getStr(String)
	 * 其它方法使用泛型返回值方法： get(String)
	 * 注意：jfinal 3.2 及以上版本 Model 中的六种 getter 方法才具有类型转换功能
	 */
	@SuppressWarnings("serial")
	protected Map<String, String> getterTypeMap = new HashMap<String, String>() {{
		put("java.lang.String", "getStr");
		put("java.lang.Integer", "getInt");
		put("java.lang.Long", "getLong");
		put("java.lang.Double", "getDouble");
		put("java.lang.Float", "getFloat");
		put("java.lang.Short", "getShort");
		put("java.lang.Byte", "getByte");
	}};
	
	public JFinalTemplateEngine() {
		engine = Engine.create("forGenerator");

        engine.addSharedMethod(new StrKit());
        engine.addSharedObject("getterTypeMap", getterTypeMap);
        engine.addSharedObject("javaKeyword", JavaKeyword.me);
	}

	/**
	 * 根据模板生成代码
	 * @return
	 */
	@Override
	public String execute(String templateFolder, String templatePath, String templateType, Map<String, Object> templateModel) {
		Engine engine = Engine.use("forGenerator");
		if("class".equalsIgnoreCase(templateType)) {
			templateFolder = templateFolder.startsWith("class:/") ? templateFolder.substring(6) : templateFolder;
			templateFolder = templateFolder.startsWith("//") ? templateFolder.substring(1) : templateFolder;
			engine.setToClassPathSourceFactory();
		} else {
			engine.setSourceFactory(new FileSourceFactory());
		}
		engine.setBaseTemplatePath(templateFolder);
		return engine.getTemplate(templatePath).renderToString(templateModel);
	}

	@Override
	public String execute(String templateContent, Map<String, Object> templateModel) {
		Engine engine = Engine.use("forGenerator");
		return engine.getTemplateByString(templateContent).renderToString(templateModel);
	}
}
